/**
 * 
 */
package org.cuatrovientos.erp.dao;

import java.util.List;

import org.cuatrovientos.erp.model.City;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author pablo_guerrero
 * Implementation of CityDAOInterface
 *
 */
public class CityDAO implements CityDAOInterface{
	@Autowired
	 private SessionFactory sessionFactory;
	
	/**
	 * Default Constructor
	 */
	public CityDAO(){
		
	}
	
	/**
	 * returns Hibernate session
	 * @return the session
	 */
	 private Session getSession () {
		 return sessionFactory.getCurrentSession();
	 }
	 
	/**
	 * @param int id
	 * @return City city
	 * This method select a city by it's id
	 */
	@Transactional(readOnly = true)
	@Override
	public City selectById(int id) {
		City city = (City) getSession().get(City.class, id);
	    return city;
	}
	
	/**
	 * @return A list of all the cities we have
	 */
	@Transactional(readOnly = true)
	@Override
	public List<City> selectAll() {
		List<City> cities = getSession().createQuery("from City").list();
	    return cities;
	}
	
	/**
	 * @return The number of cities we have in the database
	 */
	@Transactional(readOnly = true)
	@Override
	public int selectAllCount(){
		List<City> cities = getSession().createQuery("from City").list();
	    return cities.size();
	}
	
	/**
	 * @param City city
	 * This method insert the city we passed as parameter
	 */
	@Transactional
	@Override
	public void insert(City city) {
		Integer id = (Integer) getSession().save(city);
		city.setId(id);
	}
	
	/**
	 * @param City city
	 * This method updates the city we passed as parameter
	 */
	@Transactional
	@Override
	public void update(City city) {
		getSession().merge(city);	
		
	}
	
	/**
	 * @param City city
	 * This method deletes a city we passed as parameter
	 */
	@Transactional
	@Override
	public void delete(City city) {
		getSession().delete(city);
		
	}
	
	/**
	 * @param City city
	 */
	public void saveOrUpdate(City city){
			getSession().saveOrUpdate(city);
	}
	
	/**
	 * @param int id
	 * This method deletes the city selected by the id
	 */
	@Transactional(readOnly = true)
	@Override
	public void deleteById(int id) {
		City city = (City) getSession().load(City.class,id);
		getSession().delete(city);
		
	}
	
	/**
	 * @param String name
	 * This method searches all the cities which has the same name we are looking for.
	 */
	@Transactional(readOnly = true)
	@Override
	public List<City> search(String name) {
		Query query = getSession().createQuery("from City c where c.name like :name");
        query.setParameter("name", "%"+name+"%");
        List<City> cities = query.list();
		
        return cities;
	}

}
